package com.darren.euc.job;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.naming.NamingException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.darren.euc.entity.PrintRecord;
import com.darren.euc.service.PrintRecordService;
import com.darren.euc.util.PrintUtil;
import com.darren.euc.util.PropertyHelper;



@Component
public class QueryPrintRecordsTask {	

	private static final Logger log = Logger.getLogger(QueryPrintRecordsTask.class);
	private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
    private PrintRecordService printRecordService;

	/**
	 * 定时查询打印记录
	 * @throws SQLException
	 * @throws NamingException
	 */
	@Scheduled(cron = "0 * * * * ?")
	public void refreshSystemParameter() throws SQLException, NamingException {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		log.info("Refresh system parameters job launch start ..." + System.currentTimeMillis());		
		try {
			String startTime = "1900-01-01 00:00:01";
			String endTime =  FORMATTER.format(new Date());			
			PrintRecord lastRecord = printRecordService.getLastRecords();
			if(lastRecord != null && lastRecord.getJobInTime() != null){
				startTime = FORMATTER.format(lastRecord.getJobInTime());
			}
			JSONObject resultJson = PrintUtil.queryPrintRecords(PropertyHelper.getPrintQueryURL(), startTime, endTime);	
			if(resultJson != null){
				JSONArray jsonArray = resultJson.getJSONArray("job_list");
				if(jsonArray != null){
					for(int i = 0; i < jsonArray.size();i++){
						JSONObject jobs = jsonArray.getJSONObject(i);
						List<PrintRecord> printRecords =JSON.parseArray(jobs.getJSONArray("job").toString(), PrintRecord.class);
						for(PrintRecord printRecord:printRecords){
							printRecordService.save(printRecord);
						}
					}
				}
			}
			printRecordService.updateMemberInfo();
			System.out.println(resultJson.toJSONString());
		} catch (Exception e) {
		    log.error(e.getMessage(),e);
		}	
		log.info("Refresh system parameters job launch end   ..." + System.currentTimeMillis());
		stopWatch.stop();
		log.info("Refresh system parameters job launch total time ..."+ stopWatch.getTotalTimeMillis());
	}
	
	
	
}
